package com.vilicode.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@WebFilter("/*")
public class EncodeFilter implements Filter {
    String charset = "utf-8";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        charset = filterConfig.getInitParameter("charset");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //对post进行编码
        request.setCharacterEncoding(charset);
        //创建装饰类
        MyRequest req = new MyRequest((HttpServletRequest) request);
        //放行
        chain.doFilter(req, response);
    }

    @Override
    public void destroy() {

    }

    private class MyRequest extends HttpServletRequestWrapper {
        private HttpServletRequest request;
        public MyRequest(HttpServletRequest request) {
            super(request);
            this.request = request;
        }

        @Override
        public String getParameter(String name) {
            //得到原来的值
            String value = request.getParameter(name);
            //判断是否是get方法
            if (value !=null && "GET".equalsIgnoreCase(request.getMethod())) {
                try {
                    value = new String(value.getBytes("iso-8859-1"), charset);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
            return value;
        }

    }
}